/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useCallback, useRef, useEffect } from 'react';
import { connect } from 'dva';
import { Menu } from 'antd';
import { useInterval, useUpdateEffect } from 'ahooks';
import { Chart, Geom, Axis, Tooltip, Coord, Label } from 'bizcharts';
import DataSet from '@antv/data-set';
import PropTypes from 'prop-types';
import { lineStyleRow, gradualTextColumn } from '../../_utils';
import CommonBorder from '../../Wrappers/CommonBorder';
import NoDate from '../../Wrappers/NoDate';
import styles from '../../../commonChart.less';

const label = {
  // formatter(text) {
  //   return `${text}`.substr(0, 3);
  // },
  textStyle: {
    offset: 12,
    fill: gradualTextColumn, // 文本的颜色
    fontSize: '14', // 文本大小
    fontWeight: 'bold', // 文本粗细
  },
};

const ds = new DataSet();

const Histogram = ({
  dispatch,
  isParentFull,
  branchId,
  loading,
  type = 'in',
  screenToken,
  currentLevel,
  onSelect,
  showSelect,
  title,
  dispatchType,
  xKey = '',
  yKey = '',
  tooltip = [],
  cols = {},
}) => {
  const [data, setData] = useState({});
  const [hasData, setHasData] = useState(false);
  const [height, setHeight] = useState(0);
  const heightRef = useRef({});
  const timer = useRef(null);

  const fetchData = useCallback(
    () => {
      dispatch({
        type: dispatchType,
        payload: {
          token: screenToken,
          day: 1,
          cm_id: 'all',
          code: branchId,
          type,
          pageSize: 10,
          level: currentLevel,
        },
      }).then((res = []) => {
        const dv = ds.createView().source(res.reverse());
        setHasData(res.length > 0);
        setData(dv);
      });
    },
    [branchId, dispatch, type, screenToken, currentLevel],
  );

  const menu = (
    <Menu onClick={onSelect}>
      <Menu.Item key="order">昨日寄件数排名</Menu.Item>
      <Menu.Item key="gp">`昨日共配单量排名`</Menu.Item>
    </Menu>
  );

  useEffect(
    () => {
      timer.current = setTimeout(() => {
        heightRef.current && setHeight(heightRef.current.clientHeight);
      }, 1000);
      return () => {
        timer.current && clearTimeout(timer.current);
      };
    },
    [isParentFull],
  );

  useUpdateEffect(fetchData, [fetchData]);
  useInterval(fetchData, 1000 * 60 * 60);

  return (
    <CommonBorder title={title} showSelect={showSelect} menu={menu} loading={loading}>
      <div style={{ height: '100%' }} ref={heightRef}>
        {hasData ? (
          <Chart
            className={styles.chart}
            style={{ backgroundColor: 'rgba(15, 24, 55, 0.7)' }}
            height={height}
            data={data}
            forceFit
            scale={cols}
            padding={[10, 60, 'auto', 'auto']}
          >
            <Coord transpose />
            <Axis name={xKey} label={label} line={null} tickLine={null} />
            <Axis name={yKey} visible={false} />
            <Tooltip
              crosshairs={{
                type: 'x',
              }}
            />
            <Geom
              size={[[yKey], [1, 10]]}
              type="interval"
              position={`${xKey}*${yKey}`}
              shape="round-rect"
              style={lineStyleRow}
              tooltip={tooltip}
            >
              <Label content={yKey} textStyle={label.textStyle} textAlign="center" offsetX={5} />
            </Geom>
          </Chart>
        ) : (
          <NoDate title="暂无数据" style={{ height }} />
        )}
      </div>
    </CommonBorder>
  );
};

Histogram.propTypes = {
  type: PropTypes.oneOf(['in', 'order', 'pda', 'zyyl']).isRequired,
};

export default connect(({ chartData, loading, global }, { dispatchType }) => ({
  screenToken: global.screenToken,
  branchId: chartData.currentAreaInfo.branchId,
  currentLevel: chartData.currentAreaInfo.currentLevel,
  loading: loading.effects[dispatchType],
  // loading: loading.effects['chartData/getYesterdayInNum'],
}))(React.memo(Histogram));
